import {
	defineStore
} from 'pinia';

// 维护商品详情
export const useGoodsDetailStore = defineStore('goodsDetail', {
	state: () => ({
		goodsDetail: {
			goodsId: 1111111,
			imgs: [
				"/static/test/wql1.jpg",
				"https://img2.baidu.com/it/u=1221805218,3055426471&fm=253&fmt=auto&app=138&f=JPEG?w=1080&h=450"
			],
			info: '默认商品的描述，以很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长可以很长很长很长很长很长很长很长很长很长很长很长很长',
			price: "1000",
			releaseTime: "2022-05-05T19:23:33", // 发布时间
			// 卖家信息
			seller: {
				id: 666666, // 卖家 id
				name: '名字最长有八个字',
				avatar: 'https://photo.chaoxing.com/photo_80.jpg', // 头像
			},
		},
		
	}),

	actions: {
		async fetchGoodsDetail(api, goodsId, rhc) {
			try {
				const response = await uni.request({
					url: `${api}/goodsDetail/${goodsId}`,
					header: {
						'Cookie': rhc
					}
				});

				const result = response.data.data;

				if (result) {
					// 在设置商品详情前格式化发布时间
					result.releaseTime = this.formatReleaseTime(result.releaseTime);
					this.setGoodsDetail(result);
				} else {
					this.resetGoodsDetail();
				}
			} catch (error) {
				console.error("Failed to fetch goods detail:", error);
				this.resetGoodsDetail();
			}
		},

		// 设置商品详情
		setGoodsDetail(detail) {
			this.goodsDetail = detail;
		},

		// 重置商品详情
		resetGoodsDetail() {
			this.goodsDetail = {
				goodsId: null,
				imgs: [],
				info: '',
				price: '',
				releaseTime: '',
				seller: {
					id: null,
					name: '',
					avatar: ''
				}
			};
		},
		
		// 发布时间处理
		formatReleaseTime(releaseTime) {
			// 将发布时间字符串转换为 Date 对象
			const releaseDate = new Date(releaseTime);
			// 获取当前时间
			const currentDate = new Date();
		
			// 如果发布时间是今天
			if (
				releaseDate.getDate() === currentDate.getDate() &&
				releaseDate.getMonth() === currentDate.getMonth() &&
				releaseDate.getFullYear() === currentDate.getFullYear()
			) {
				return `今日${releaseDate.getHours()}时${releaseDate.getMinutes()}分`;
			}
		
			// 如果发布时间是昨天
			const yesterday = new Date(currentDate);
			yesterday.setDate(yesterday.getDate() - 1);
			if (
				releaseDate.getDate() === yesterday.getDate() &&
				releaseDate.getMonth() === yesterday.getMonth() &&
				releaseDate.getFullYear() === yesterday.getFullYear()
			) {
				return `昨日${releaseDate.getHours()}时${releaseDate.getMinutes()}分`;
			}
		
			// 如果发布时间是一年内
			if (currentDate.getFullYear() === releaseDate.getFullYear()) {
				return `${releaseDate.getMonth() + 1}月${releaseDate.getDate()}日${releaseDate.getHours()}时${releaseDate.getMinutes()}分`;
			}
		
			// 如果发布时间超过一年
			return `${releaseDate.getFullYear()}年${releaseDate.getMonth() + 1}月${releaseDate.getDate()}日${releaseDate.getHours()}时${releaseDate.getMinutes()}分`;
		}
	},

	getters: {
		// 此处不再需要 getters 处理发布时间
	}
});
